package androidvn.xenforo.fourums;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;

import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidvn.xenforo.fourums.R;
import androidvn.xenforo.fourums.model.User;
import androidvn.xenforo.fourums.widget.JsonParser;

public class GetUserFragment extends ListFragment {
	private ProgressDialog pDialog;
	JsonParser jsonParser = new JsonParser();

	int groupPosition, childPosition;
	private User user = new User();
	private String avatarUrl;
	private ArrayList<String> userStr = new ArrayList<String>();
	private View headerView;
	private TextView tvUsername;
	private ImageView ivAvatar;
	// private ImageLoader imageLoader;
	private int icLoader = R.drawable.ic_loader;
	// JSON url
	private final static String url_user = "http://android.vn/api.php?action=getUser";
	// private final static String url_avatar =
	// "http://android.vn/api.php?action=getAvatar";
	// ALL JSON node names
	private final static String TAG_USER_ID = "user_id";
	private final static String TAG_USERNAME = "username";
	private final static String TAG_GENDER = "gender";
	private final static String TAG_MESSAGE_COUNT = "message_count";
	private final static String TAG_CONVERSATION_UNREAD = "conversations_unread";
	private final static String TAG_RESGITER_DATE = "register_date";
	private final static String TAG_LAST_ACTIVITY = "last_activity";
	private final static String TAG_ALERTS_UNREAD = "alerts_unread";
	private final static String TAG_LIKE_COUNT = "like_count";
	private final static String TAG_TROPHY_POINTS = "trophy_points";
	private final static String TAG_WARNING_POINTS = "warning_points";

	// private static final String TAG_BOX = "nameBox";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);

		View view = inflater
				.inflate(R.layout.get_user_layout, container, false);
		headerView = inflater.inflate(R.layout.get_user_header, null);
		tvUsername = (TextView) headerView.findViewById(R.id.tvUsername);
		ivAvatar = (ImageView) headerView.findViewById(R.id.ivAvatar);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		new LoadData().execute();

		if (headerView != null) {
			getListView().addHeaderView(headerView);

		}

		getListView().setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				//
			}
		});
	}

	class LoadData extends AsyncTask<String, String, String> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(getActivity());
			pDialog.setMessage("Loading ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected String doInBackground(String... arg0) {
			// parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("hash", Global.userName + ":"
					+ Global.userHash));
			// getAvatar
			// JSONObject jsonRespondAvatar = jsonParser.makeHttpRequest(
			// url_avatar, "GET", params);
			// // Log.d("JSON RESPOND AVATAR >>>",
			// jsonRespondAvatar.toString());
			// if (jsonRespondAvatar != null) {
			// try {
			// avatarUrl = jsonRespondAvatar.getString("avatar");
			// } catch (JSONException e) {
			// e.printStackTrace();
			// }
			// avatarUrl.substring(17, 50);
			//
			// }

			// getUser
			JSONObject jsonRespondUser = jsonParser.makeHttpRequest(url_user,
					"GET", params);

			// Log.d("JSON RESPOND USER >>>", jsonRespondUser.toString());
			if (jsonRespondUser != null) {
				try {
					user.setUserId(jsonRespondUser.getString(TAG_USER_ID));
					user.setUserName(jsonRespondUser.getString(TAG_USERNAME));
					user.setGender(jsonRespondUser.getString(TAG_GENDER));
					user.setMessageCount(jsonRespondUser
							.getString(TAG_MESSAGE_COUNT));
					user.setConversationUnread(jsonRespondUser
							.getString(TAG_CONVERSATION_UNREAD));
					//

					user.setRegisterDate(DateFormat.getDateInstance().format(
							new Date(Long.valueOf(jsonRespondUser
									.getString(TAG_RESGITER_DATE) + "000"))));
					user.setLastActivity(DateFormat.getDateInstance().format(
							new Date(Long.valueOf(jsonRespondUser
									.getString(TAG_LAST_ACTIVITY) + "000"))));
					//
					user.setTrophyPoints(jsonRespondUser
							.getString(TAG_TROPHY_POINTS));
					user.setAlertsUnread(jsonRespondUser
							.getString(TAG_ALERTS_UNREAD));
					user.setLikeCount(jsonRespondUser.getString(TAG_LIKE_COUNT));
					user.setWarningPoints(jsonRespondUser
							.getString(TAG_WARNING_POINTS));

					userStr.add(padRight("Giới tính:", 20)
							+ padLeft(user.getGender(), 20));
					userStr.add(padRight("Bài đã gửi:", 20)
							+ padLeft(user.getMessageCount(), 20));
					userStr.add(padRight("Tin nhắn:", 20)
							+ padLeft(user.getConversationUnread(), 20));
					userStr.add(padRight("Ngày đăng ký:", 20)
							+ padLeft(user.getRegisterDate(), 20));
					userStr.add(padRight("Hoạt động gần nhất:", 20)
							+ padLeft(user.getLastActivity(), 20));
					userStr.add(padRight("Thông báo mới:", 20)
							+ padLeft(user.getAlertsUnread(), 20));
					userStr.add(padRight("Được thích:", 20)
							+ padLeft(user.getLikeCount(), 20));
					userStr.add(padRight("Điểm thưởng:", 20)
							+ padLeft(user.getTrophyPoints(), 20));
					userStr.add(padRight("Cảnh cáo:", 20)
							+ padLeft(user.getWarningPoints(), 20));

				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			pDialog.dismiss();
			getActivity().runOnUiThread(new Runnable() {
				public void run() {
					Log.d("img loader", avatarUrl + " / " + icLoader + " / "
							+ ivAvatar);
					// imageLoader.DisplayImage(avatarUrl, icLoader, ivAvatar);
					tvUsername.setText(user.getUserName());
					setListAdapter(new ArrayAdapter<String>(getActivity(),
							android.R.layout.simple_list_item_1, userStr));
				}
			});

		}

		public String padRight(String s, int n) {
			return String.format("%1$-" + n + "s", s);
		}

		public String padLeft(String s, int n) {
			return String.format("%1$" + n + "s", s);
		}
	}

}